package com.boyinet.activation.security.filter;

import com.boyinet.activation.entity.SecurityUser;
import com.boyinet.activation.entity.User;
import com.boyinet.activation.util.JsonUtils;
import com.boyinet.activation.util.R;
import com.boyinet.activation.util.ResponseUtil;
import com.boyinet.activation.util.TokenManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;

/**
 * @author lengchunyun
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private final TokenManager tokenManager;
    private final StringRedisTemplate stringRedisTemplate;
    private final AuthenticationManager authenticationManager;

    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, StringRedisTemplate stringRedisTemplate) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.stringRedisTemplate = stringRedisTemplate;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login", "POST"));
    }

    /**
     * 1 获取表单提交用户名和密码
     *
     * @param request  http请求
     * @param response http响应
     * @return 认证
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        //获取表单提交数据
        try {
            User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(),
                    new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 2 认证成功调用的方法
     *
     * @param request    http请求
     * @param response   http响应
     * @param chain      过滤器链
     * @param authResult 认证结果
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {
        //认证成功，得到认证成功之后用户信息
        SecurityUser user = (SecurityUser) authResult.getPrincipal();
        //根据用户名生成token
        String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
        //把用户名称和用户权限列表放到redis

        stringRedisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(),
                Objects.requireNonNull(JsonUtils.serialize(user.getPermissionValueList())));
        user.getCurrentUserInfo().setPassword("");
        user.getCurrentUserInfo().setToken(token);
        //返回token
        ResponseUtil.out(response, R.ok().put("user", user.getCurrentUserInfo()));
    }

    /**
     * 3 认证失败调用的方法
     *
     * @param request  http请求
     * @param response http响应
     * @param failed   异常类型
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)
            throws IOException, ServletException {
        ResponseUtil.out(response, R.error("用户名或密码错误"));
    }
}
